home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 10430 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.6 KB  |  45 lines

  1. Newsgroups: comp.lang.c++
  2. Path: in2.uu.net!allegra!alice!ark
  3. From: ark@research.att.com (Andrew Koenig)
  4. Subject: Re: Can copy constructor and operator= share code?
  5. Message-ID: <DnvICD.5DJ@research.att.com>
  6. Organization: AT&T Research, Murray Hill NJ
  7. References: <4h2kcn$40d@rap.SanDiegoCA.ATTGIS.COM> <199603040709.a35476@iz.maus.de> <4hk3bh$1j4s@flute.aix.calpoly.edu>
  8. Date: Thu, 7 Mar 1996 01:19:25 GMT
  9.  
  10. In article <4hk3bh$1j4s@flute.aix.calpoly.edu> mporcell@flute.aix.calpoly.edu (Michael Anthony Porcelli) writes:
  11.  
  12. > Here's a style tip from a senior level C++/OO class on exactly this topic.  
  13. > In fact our teacher *required* this for all of our classes and frankly I
  14. > believe this is a GREAT C++ tip for good OO/SoftEng.
  15.  
  16. Well, almost.  See below.
  17.  
  18. > X(X& x) 
  19. >  { Duplicate(x); } //one-statement, in-line copy constructor.
  20.  
  21. > operator= (X& x) 
  22. >  { Delete(); Duplicate(x); } //two-statement, in-line op=
  23.  
  24. Oops!  This fails when you try to assign an object to itself,
  25. because it destroys the objects value and then assigns the destroyed
  26. value to itself.  It also implicitly returns an undefined integer
  27. value, instead of returning a reference to the left-hand side
  28. the way the built-in assignment operator does.  Finally, the
  29. operand should be const.
  30.  
  31. My revised version:
  32.  
  33.   X& operator=(const X& x)
  34.    { if (this != &x) { Delete(); Duplicate(x); } return *this; }
  35.  
  36. > ~X() 
  37. >  { Delete(); } //one-statement, in-line destructor.
  38.  
  39. > Pretty nifty, eh?  I believe that all class design should be done this way.
  40.  
  41. It's a good strategy if you fix the bugs described above.
  42. -- 
  43.                 --Andrew Koenig
  44.                   ark@research.att.com
  45.